package chpt11;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCPClient {
	public static void main(String[] args) {
		int port = 9000;
		InetAddress server_addr = null;
		try {
			server_addr = InetAddress.getByName("localhost");

		} catch (UnknownHostException e1) {

			e1.printStackTrace();
		}
		try (   // 创建一个Socket并连接到服务器
				Socket client = new Socket(server_addr, port);
				// 获取输出流，用于向服务器发送消息
				PrintWriter writer = new PrintWriter(client.getOutputStream());
				// 获取输入流，用于接收服务器返回的消息
				BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
				// 获取标准输入流，用于从控制台读取用户的输入
				BufferedReader in = new BufferedReader(new InputStreamReader(System.in));) {
			while (true) {
				System.out.print("Client:");
				String line = in.readLine();
				// 向服务器发送消息
				writer.println(line);
				// 刷新输出，确保消息通过网络发送到服务器
				writer.flush();
				if (line.equals("bye")) {
					break;
				}
				System.out.print("Server:");
				// 读取服务器返回的消息并打印到标准输出
				System.out.println(reader.readLine());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
